#pragma once
#include<iostream>
#include<string>
#include<cstring>
#include<cassert>
#include<functional>
#include<pthread.h>
class Thread;
//上下文
class Context
{
public:
    Thread *_this;
    void* _args;
public:
    Context():_this(nullptr),_args(nullptr)
    {}
    ~Context()
    {}
};

class Thread
{
public:
    typedef std::function<void*(void*)> func_t;
    const int num=1024;
public:
    Thread(func_t func,void* args,int number)
    :_func(func)
    ,_args(args)
    {
        char buffer[num];//变长数组
        snprintf(buffer,sizeof buffer,"thread-%d",number);
        _name=buffer;
         Context *ctx=new Context();
        ctx->_this=this;
        ctx->_args=_args;
        int n=pthread_create(&_tid,nullptr,start_routine,ctx);
        assert(n==0);
        (void)n;
    }
    //在类内创建线程，想让线程执行对应方法，需要将方法设置为static
    static void* start_routine(void* args)//如果无static，那么有缺省参数，动态THIS
    {
        //静态方法不能调用成员方法或成员变量
        Context* ctx=static_cast<Context *>(args);
        void* ret=ctx->_this->run(ctx->_args);
        delete ctx;
        return ret;
    }

    void join()
    {
        int n=pthread_join(_tid,nullptr);
        assert(n==0);
        (void)n;

    }
    void *run(void* args)
    {
        return _func(args);
    }
    ~Thread()
    {
        //do nothing
    }
private:
    std::string _name;
    pthread_t _tid;
    func_t _func;
    void* _args;
};